package com.example;

import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class Client {
    int port;
    String ip;
    Channel channel;
    EventLoopGroup workGroup = new NioEventLoopGroup();
    ChannelFuture channelFuture;

    /**
     * Constructor
     * 
     * @param port {@link Integer} port of server
     */
    public Client(int port, String ip) {
        this.port = port;
        this.ip = ip;

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                // System.out.println("here ");
                send_data_test();
            }
        }, 1000, 1000);

        System.out.println("int ");
    }

    private void send_data_test() {
        JSONObject object = new JSONObject();
        object.put("method", "keeplive");
        object.put("user", "13599895937");
        object.put("check", "fuck");

        System.out.println(JSON.toJSONString(object));
        send_data(JSON.toJSONString(object));
    }

    private void send_data(String buf) {
        // this.channel.writeAndFlush(buf);

        if (channelFuture.isSuccess()) {
            // send message to server
            channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer(buf.getBytes()))
                    .addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            System.out.println(
                                    future.isSuccess() ? "Message sent to server : Hello" : "Message sending failed");
                        }
                    });
        } else {

            System.out.println("error ");
        }
    }

    /**
     * Startup the client
     * 
     * @return {@link ChannelFuture}
     * @throws Exception
     */
    public ChannelFuture startup() throws Exception {
        try {
            Bootstrap b = new Bootstrap();
            b.group(workGroup);
            b.channel(NioDatagramChannel.class);
            b.handler(new ChannelInitializer<DatagramChannel>() {
                protected void initChannel(DatagramChannel datagramChannel) throws Exception {
                    datagramChannel.pipeline().addLast(new NettyHandler());
                }
            });
            channelFuture = b.connect(this.ip, this.port).sync();
            this.channel = channelFuture.channel();

            return channelFuture;
        } finally {
        }
    }

    /**
     * Shutdown a client
     */
    public void shutdown() {
        workGroup.shutdownGracefully();
    }
}
